package com.mune.gulimall.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.mune.common.to.MemberSessionTo;
import com.mune.common.to.mq.SeckillOrderTo;
import com.mune.common.utils.R;
import com.mune.gulimall.seckill.config.KillConstant;
import com.mune.gulimall.seckill.config.interceptor.LoginInterceptor;
import com.mune.gulimall.seckill.feign.CouponFeignService;
import com.mune.gulimall.seckill.feign.ProductFeignService;
import com.mune.gulimall.seckill.service.SeckillService;
import com.mune.gulimall.seckill.to.SecKillSkuRedisTo;
import com.mune.gulimall.seckill.vo.SeckillSessionWithSkus;
import com.mune.gulimall.seckill.vo.SkuInfoVo;
import org.apache.commons.lang.StringUtils;
import org.bouncycastle.asn1.sec.SECNamedCurves;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class SeckillServiceImpl implements SeckillService {
  @Autowired
  CouponFeignService couponFeignService;

  @Autowired
  ProductFeignService productFeignService;

  @Autowired
  StringRedisTemplate redisTemplate;

  @Autowired
  RedissonClient redissonClient;
  @Autowired
  RabbitTemplate rabbitTemplate;

  @Override
  public void uploadSeckillSkuLatest3Days() {

    // 扫描需要秒杀的活动
    R r = couponFeignService.getLates3DaysSession();
    if (r.getCode() == 0) {
      List<SeckillSessionWithSkus> sessionData = r.getData(new TypeReference<List<SeckillSessionWithSkus>>() {
      });
      saveSessionInfos(sessionData);
      saveSkuInfos(sessionData);
    }
  }

  @Override
  public List<SecKillSkuRedisTo> getCurrentSeckillSkus() {

    long time = new Date().getTime();
    Set<String> keys = redisTemplate.keys(KillConstant.KILL_CACHE_PREFIX + "*");
    for (String key : keys) {
      String startAccept = key.replace(KillConstant.KILL_CACHE_PREFIX, "");
      String[] times = startAccept.split("-");
      long startTime = Long.parseLong(times[0]);
      long endTime = Long.parseLong(times[1]);
      if (time >= startTime && time <= endTime) {
        List<String> range = redisTemplate.opsForList().range(key, 0, -1);
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(KillConstant.KILL_SKU_CACHE_PREFIX);
        List<String> list = hashOps.multiGet(range);
        if (list != null && list.size() > 0) {
          List<SecKillSkuRedisTo> collect = list.stream().map(item -> {
            SecKillSkuRedisTo redisTo = JSON.parseObject(item, SecKillSkuRedisTo.class);
            return redisTo;
          }).collect(Collectors.toList());
          return collect;
        }
        break;
      }
    }
    return null;
  }

  @Override
  public SecKillSkuRedisTo getSkuSeckillInfo(Long skuId) {
    BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(KillConstant.KILL_SKU_CACHE_PREFIX);
    Set<String> keys = ops.keys();
    if (keys != null && keys.size() > 0) {
      String regx = "\\d-" + skuId;
      for (String key : keys) {
        if (Pattern.matches(regx, key)) {
          String json = ops.get(key);
          SecKillSkuRedisTo redisTo = JSON.parseObject(json, SecKillSkuRedisTo.class);
          Long startTime = redisTo.getStartTime();
          Long endTime = redisTo.getEndTime();
          long time = new Date().getTime();
          if (!( time >= startTime && time <= endTime )) {
            redisTo.setRandomCode(null);
          }
          return redisTo;
        }
      }
    }
    return null;
  }

  @Override
  public String kill(String killId, String code, Integer num) {
    //获取当前用户的信息
    MemberSessionTo user = LoginInterceptor.orderThread.get();
    BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(KillConstant.KILL_SKU_CACHE_PREFIX);
    String skuJson = ops.get(killId);
    if (StringUtils.isEmpty(skuJson)) return null;
    SecKillSkuRedisTo redisTo = JSON.parseObject(skuJson, SecKillSkuRedisTo.class);
    // 校验合法性
    Long startTime = redisTo.getStartTime();
    Long endTime = redisTo.getEndTime();
    long time = new Date().getTime();
    if (time < startTime || time > endTime) return null;
    // 验证随机码和 场次-skuId是否相同
    String randomCode = redisTo.getRandomCode();
    String paramKey = redisTo.getPromotionSessionId() + "-" + redisTo.getSkuId();
    if (!redisTo.getRandomCode().equals(code) || !paramKey.equals(killId)) return null;
    Integer seckillLimit = redisTo.getSeckillLimit();
    // 获取当前信号量数量
    String seckillCount = redisTemplate.opsForValue().get(KillConstant.KILL_SKU_STOCK_SEMAPHORE + randomCode);
    Integer count = Integer.valueOf(seckillCount);
    // 信号量为0（已经秒杀完） || 要购买的数量超过限购的数量 || 购买的数量超过信号量    都视为失败
    if (count == 0 || num > seckillLimit || num > count) return null;
    String redisKey = user.getId() + "-" + paramKey;
    // 设置过期时间
    long ttl = endTime - startTime;
    // 如果redis中已经存在消息,则表明已经购买过
    Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
    if (!aBoolean) return null;
    RSemaphore semaphore = redissonClient.getSemaphore(KillConstant.KILL_SKU_STOCK_SEMAPHORE + randomCode);
    try {
      boolean semaphoreCount = semaphore.tryAcquire(num, 100, TimeUnit.MILLISECONDS);
      if (semaphoreCount) {
        String timeId = IdWorker.getTimeId();
        SeckillOrderTo seckillOrderTo = new SeckillOrderTo();
        seckillOrderTo.setMemberId(user.getId());
        seckillOrderTo.setNum(num);
        seckillOrderTo.setOrderSn(timeId);
        seckillOrderTo.setPromotionSessionId(redisTo.getPromotionSessionId());
        seckillOrderTo.setSkuId(redisTo.getSkuId());
        seckillOrderTo.setSeckillPrice(redisTo.getSeckillPrice());
        rabbitTemplate.convertAndSend("order-event-exchange", "order.seckill.order");
        return timeId;
      }
    } catch (InterruptedException e) {
      return null;
    }
    return null;
  }

  private void saveSessionInfos(List<SeckillSessionWithSkus> sessionData) {
    sessionData.forEach(session -> {
      long startTime = session.getStartTime().getTime();
      long endTime = session.getEndTime().getTime();
      String key = KillConstant.KILL_CACHE_PREFIX + startTime + "-" + endTime;
      Boolean hasKey = redisTemplate.hasKey(key);
      if (!hasKey) {
        List<String> value = session.getRelationSkus().stream().map(item -> item.getPromotionSessionId() + "-" + item.getSkuId()).collect(Collectors.toList());
        redisTemplate.opsForList().leftPushAll(key, value);
      }
    });
  }

  private void saveSkuInfos(List<SeckillSessionWithSkus> sessionData) {
    sessionData.forEach(session -> {
      BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(KillConstant.KILL_SKU_CACHE_PREFIX);
      session.getRelationSkus().forEach(seckillSkuVo -> {
        Long skuId = seckillSkuVo.getSkuId();

        String key = seckillSkuVo.getPromotionSessionId() + "-" + skuId;
        Boolean hasKey = ops.hasKey(key);
        if (!hasKey) {
          // 缓存商品
          SecKillSkuRedisTo redisTo = new SecKillSkuRedisTo();
          // sku的基本数据
          R info = productFeignService.getSkuInfo(seckillSkuVo.getSkuId());
          if (info.getCode() == 0) {
            SkuInfoVo data = info.getData("skuInfo", new TypeReference<SkuInfoVo>() {
            });
            redisTo.setSkuInfo(data);
          }
          // sku的秒杀信息对拷
          BeanUtils.copyProperties(seckillSkuVo, redisTo);

          // 设置上当前商品的秒杀时间信息
          redisTo.setStartTime(session.getStartTime().getTime());
          redisTo.setEndTime(session.getEndTime().getTime());

          // 设置随机码
          String token = UUID.randomUUID().toString().replace("-", "");
          redisTo.setRandomCode(token);
          // 设置Redisson分布式信号量，让秒杀库存作为信号量
          RSemaphore semaphore = redissonClient.getSemaphore(KillConstant.KILL_SKU_STOCK_SEMAPHORE + token);
          semaphore.trySetPermits(seckillSkuVo.getSeckillCount());
          String value = JSON.toJSONString(redisTo);
          ops.put(key, value);
        }
      });
    });
  }
}
